
//获取应用实例
const app = getApp()
Page({
    data: {
        //判断小程序的API，回调，参数，组件等是否在当前版本可用。
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        isHide: false,
        userInfo: {},
        colleges: [],
        college_o:[],
        hasUserInfo: false,
        isuserbind: false,
        inputusername: '',
        inputpassword: '',
        localinfo: '',
        index:0,
        loading:false,
        college:"",
        collegeVisible:false,
        collegeName:''
    },
    onLoad: function() {
        var that = this;
        // 查看是否授权
        console.log("onLoad")
        wx.getSetting({
            success: function(res) {
                if (res.authSetting['scope.userInfo']) {
                    wx.getUserInfo({
                        success: function(res) {
                            app.globalData.userInfo = res.userInfo;
                            wx.login({
                              success: res => {
                                  wx.request({
                                    url: `${app.globalData.support_url}/wechat/get_xcx_user?code=${res.code}`,
                                    method: 'get',
                                    header: {
                                      'content-type': 'application/json'
                                    },
                                    success: res2 => {
                                      if(res2.statusCode===200){
                                          const unionid=res2.data.unionid;
                                          const access_key=res2.data.session_key;
                                          wx.setStorageSync('unionid', unionid);
                                          app.globalData.unionid=unionid;
                                          app.globalData.access_key=access_key;
                                          wx.request({
                                            url: app.globalData.support_url +'/wechat/get_bind_sys?unionid='+unionid,     
                                            method: 'get',
                                            header: {
                                              'content-type': 'application/json'
                                            },
                                            success: res3 => {
                                              if(res3.statusCode===200){
                                                  if(!res3.data){
                                                    that.getColleges();
                                                }else{
                                                  app.globalData.url=res3.data.sys;
                                                  wx.request({
                                                    url: app.globalData.url+'/wechat/get_user_by_unionid?unionid='+app.globalData.unionid,
                                                method: 'get',
                                                 header: {
                                                  'content-type': 'application/json'
                                                 },
                                                success: res4 => {
                                                  if (res4.data.status == 'fail') {
                                                    app.globalData.localuserinfo = {};
                                                    this.setData({
                                                      isuserbind: false,
                                                      localinfo: "",
                                                      loading: false
                                                    })
                                                  } else {
                                                    var localuserinfo = res4.data;
                                                    app.globalData.localuserinfo=res4.data
                                                    that.setData({
                                                      isuserbind: true,
                                                      localinfo: "用户名:" + localuserinfo.username + " ，名字:" + localuserinfo.showName,
                                                      loading: false
                                                    })
                                                    if (localuserinfo.isTeacher != null && localuserinfo.isTeacher==true){
                                                      wx.redirectTo({
                                                        url: '../teacher_home/home',
                                                        fail:res=>{
                                                          console.log("fail");
                                                          console.log(res);
                                                        },
                                                      })
                                                    } else {
                                                      wx.redirectTo({
                                                        url: '../student_home/home',
                                                        fail:res=>{
                                                          console.log("fail");
                                                          console.log(res);
                                                        },
                                                      })
                                                    }
                                                  }
                                                }
                                              })
                                                }
                                              }
                                            }
                                          })
                                      }
                                    },
                                    fail:res=>{
                                      console.log("fail");
                                      console.log(res);
                                    },
                                  })
                              }
                      })   
                              }
                    });
                } else {
                    // 用户没有授权
                    // 改变 isHide 的值，显示授权页面
                    that.setData({
                        isHide: true
                    });
                }
            }
        });
    },
    bind: function () {
      var that = this;
      if(this.data.college == ""){
        wx.showToast({
          title: '请选择绑定的作业平台',
          icon: 'none',
          duration: 2000
        })
      }
      else if (this.data.inputusername == "" || this.data.inputpassword == "") {
        wx.showToast({
          title: '请填写交作业系统用户登录名及密码',
          icon: 'none',
          duration: 2000
        })
      } else {
        that.setData({
          loading:true
        })
        this.bindSupportSys()
        wx.request({
          url: app.globalData.url+'/api/v1/login',
          data: {
            username: this.data.inputusername,
            password: this.data.inputpassword
          },
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          success: res => {
            if (res.data.error) {
              wx.showToast({
                title: res.data.error,
                icon: 'none',
                duration: 2000
              })
              this.setData({
                isuserbind: false,
                localinfo: "",
                loading:false
              })
            } else {
              var localuserinfo = res.data;
              app.globalData.localuserinfo = localuserinfo;
              wx.request({
                url: app.globalData.url +'/wechat/bind_unionid_to_user',
                data: {
                  unionid: app.globalData.unionid,
                  username: this.data.inputusername,
                  token:app.globalData.token
                },
                method: 'POST',
                header: {
                  'content-type': 'application/json'
                },
                success: res => {
                  if (res.data.status == 'fail') {
                    app.globalData.localuserinfo = {};
                    this.setData({
                      isuserbind: false,
                      localinfo: "",
                      loading: false
                    })
                  } else {
                    var localuserinfo = res.data;
                    this.setData({
                      isuserbind: true,
                      localinfo: "用户名:" + localuserinfo.username + " ，名字:" + localuserinfo.showName,
                      loading: false
                    })
                    if (localuserinfo.isTeacher != null && localuserinfo.isTeacher==true){
                      wx.redirectTo({
                        url: '../teacher_home/home',
                        fail:res=>{
                          console.log("fail");
                          console.log(res);
                        },
                      })
                    } else {
                      wx.redirectTo({
                        url: '../student_home/home',
                        fail:res=>{
                          console.log("fail");
                          console.log(res);
                        },
                      })
                    }
                  }
                }
              })
            }
          },
          fail:res=>{
            console.log("login fail")
            //console.log(res);
            wx.showToast({
              title: "连接服务器出错，绑定失败",
              icon: 'none',
              duration: 2000
            })
            that.setData({
              loading: false
            })
          }
        });
      }
    },
    bindSupportSys:function(){
      wx.request({
        url: app.globalData.support_url+'/wechat/bind_sys_to_user',
    method: 'post',
    data: {
      unionid: app.globalData.unionid,
      sys: app.globalData.url,
    },
     header: {
      'content-type': 'application/json'
     },
    success: res4 => {
    
    }
  })
    },
    bindKeyInput: function (e) {
      this.setData({
        inputusername: e.detail.value
      })
    },
    bindKeypasswordInput: function (e) {
      this.setData({
        inputpassword: e.detail.value
      })
    },
    bindGetUserInfo: function(e) {
        if (e.detail.userInfo) {
            //用户按了允许授权按钮
            var that = this;
            // 获取到用户的信息了，打印到控制台上看下
                  app.globalData.userInfo = e.detail.userInfo;
                  wx.login({
                      success: res => {
                          // 获取到用户的 code 之后：res.code
                          // 可以传给后台，再经过解析获取用户的 openid
                          // 或者可以直接使用微信的提供的接口直接获取 openid ，方法如下：
                          wx.request({
                            url: `${app.globalData.support_url}/wechat/get_xcx_user?code=${res.code}`,
                            method: 'get',
                            header: {
                              'content-type': 'application/json'
                            },
                            success: res2 => {
                              if(res2.statusCode===200){
                                  const unionid=res2.data.unionid;
                                  const access_key=res2.data.session_key;
                                  wx.setStorageSync('unionid', unionid);
                                  app.globalData.unionid=unionid;
                                  app.globalData.access_key=access_key;
                                  wx.request({
                                    url: app.globalData.support_url +'/wechat/get_bind_sys?unionid='+unionid,     
                                    method: 'get',
                                    header: {
                                      'content-type': 'application/json'
                                    },
                                    success: res3 => {
                                      if(res3.statusCode===200){
                                          if(!res3.data){
                                            that.getColleges();
                                        }else{
                                          app.globalData.url=res3.data.sys;
                                          wx.request({
                                            url: app.globalData.url+'/wechat/get_user_by_unionid?unionid='+app.globalData.unionid,
                                        method: 'get',
                                         header: {
                                          'content-type': 'application/json'
                                         },
                                        success: res4 => {
                                          if (res4.data.status == 'fail'||res4.data.error) {
                                            app.globalData.localuserinfo = {};
                                            that.getColleges();
                                            this.setData({
                                              isuserbind: false,
                                              localinfo: "",
                                              loading: false
                                            })
                                          } else {
                                            var localuserinfo = res4.data;
                                            app.globalData.localuserinfo=res4.data
                                            this.setData({
                                              isuserbind: true,
                                              localinfo: "用户名:" + localuserinfo.username + " ，名字:" + localuserinfo.showName,
                                              loading: false
                                            })
                                            if (localuserinfo.isTeacher != null && localuserinfo.isTeacher==true){
                                              wx.redirectTo({
                                                url: '../teacher_home/home',
                                                fail:res=>{
                                                  console.log("fail");
                                                  console.log(res);
                                                },
                                              })
                                            } else {
                                              wx.redirectTo({
                                                url: '../student_home/home',
                                                fail:res=>{
                                                  console.log("fail");
                                                  console.log(res);
                                                },
                                              })
                                            }
                                          }
                                        }
                                      })
                                        }
                                      }
                                    }
                                  })
                              }
                            
                            }
                          })
                      }
              })   
            //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
            that.setData({
                isHide: false
            });
        } else {
            //用户按了拒绝按钮
            wx.showModal({
                title: '警告',
                content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
                showCancel: false,
                confirmText: '返回授权',
                success: function(res) {
                    // 用户没有授权成功，不需要改变 isHide 的值
                    if (res.confirm) {
                        console.log('用户点击了“返回授权”');
                    }
                }
            });
        }
    },
    getColleges:function(){
      const that =this;
      wx.request({
        url: app.globalData.support_url+'/wechat/get_college',
    method: 'get',
     header: {
      'content-type': 'application/json'
     },
    success: res4 => {
      const _colleges=res4.data
      const colleges=_colleges.map(s=>{return {label:s.name,value:s.name}})
      that.setData({colleges,college_o:_colleges})
    }
  })
    },
    onPickerCancel:function(){
      this.setData({collegeVisible:false})
    },
    onPickerChange:function(e){
      const collegeInfo=this.data.college_o.find(c=>c.name===e.detail.value[0]);
      app.globalData.url=collegeInfo.address;
      this.setData({college:e.detail.value})
    },
    onClickPicker:function(){
      this.setData({collegeVisible:true})
    }
})
